<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/27 0027
 * Time: 上午 11:26
 */
namespace app\api\service;

use app\admin\model\Coupon;
use app\admin\model\Couponuse;
use app\api\controller\Integral;
use app\common\DictConstant;
use app\common\model\Ordercommission;
use app\common\model\Product;
use app\common\BaseHelper;
use app\common\model\Orderproductdetail;
use app\common\model\Productspecgroups;
use app\common\model\Proofrefund;
use app\common\model\Refundorder;
use app\common\model\User;
use app\common\model\Useraddress;
use app\common\model\Usermemberhistory;
use app\lib\exception\OrderException;
use app\lib\exception\ParameterException;
use app\lib\exception\UserException;
use think\Db;
use think\Exception;
use think\Log;

class Order{

//    protected $product = [
//        [
//            'productId' => 3,
//            'count' =>3,
//            'specid' => 22
//        ],
//        [
//            'productId' => 4,
//            'count' =>1,
//            'specid' => 23
//        ],
//        [
//            'productId' => 5,
//            'count' =>2,
//            'specid' => 24
//        ],
//
//    ];

    //订单商品列表，也就是客户端传过来的products
    protected $oProducts;

    //真实的商品信息，从数据库查出来的（包括库存量）
    protected $products;
    protected $uid;
    protected $tenantid;
    protected $storeid;
    protected $orderId;
    protected $ordertype;
    protected $deliverAddress = NULL;
    protected $userName = NULL;
    protected $userPhone = NULL;
    protected $subscribeDate = NULL;
    protected $saleRuleId = NULL;
    protected $content = NULL;
    protected $couponId = NULL;
    protected $memberId = NULL;
    protected $freight = 0;
    protected $packingfee = 0;
    protected $oldSaleMoney = 0;
    protected $oldMemberPrice = 0;

    /**
     * 创建订单入口
     * @param $uid
     * @param $orderdata
     * @param $oProducts
     * @return array
     * @throws ParameterException
     */
    public function place($uid,$orderdata,$oProducts){
        //oProducts和products进行对比
        $this->oProducts = $oProducts;
        $this->products = $this->getProductsByOrder($oProducts);
        $this->uid = $uid;
        $this->orderId = $orderdata['orderId'];
        $this->tenantid = $orderdata['tenantid'];
        $this->storeid = isset($orderdata['storeId'])?$orderdata['storeId']:null;
        $this->ordertype = $orderdata['orderType'];
        $this->saleRuleId = isset($orderdata['saleRuleId'])?$orderdata['saleRuleId']:null;
        $this->content = isset($orderdata['content'])?$orderdata['content']:null;
        $this->couponId = isset($orderdata['couponId'])?$orderdata['couponId']:null;
        $this->memberId = isset($orderdata['memberId'])?$orderdata['memberId']:null;
        $this->freight = isset($orderdata['freight'])?$orderdata['freight']:0;
        $this->packingfee = isset($orderdata['packingfee'])?$orderdata['packingfee']:0;
        if($orderdata['orderType'] == DictConstant::ORDER_TYPE_ONLINE){
            if($this->ischeckaddress($orderdata)){
                $this->deliverAddress = $orderdata['deliverAddress'];
                $this->userName = $orderdata['userName'];
                $this->userPhone = $orderdata['userPhone'];
            }else{
                throw new ParameterException([
                    'msg' => '用户收货信息异常！',
                ]);
            }
        }
        //线下订单为预约到店时间  线上订单为提示商家发货的时间
        if(isset($orderdata['subscribeDate']) && !empty($orderdata['subscribeDate'])){
            $this->subscribeDate = $orderdata['subscribeDate'];
        }

        $status = $this->getOrderStatus();

        if(!$status['pass']){
            $status['order_id'] = -1;
            return $status;
        }

        //如果客户端传递了优惠券id或者会员卡id（表示该订单存在优惠）
        if($this->couponId){
            $Couponuse = Couponuse::where(['couponId'=>$this->couponId,'userId'=>$this->uid,'status'=>0])->find();
            if($Couponuse){
                $Coupondetails = json_decode($Couponuse->couponDetail,true);
                if($status['orderPrice']>=$Coupondetails['value1']){
                    $status['orderPrice']-=$Coupondetails['value2'];
                    $this->oldSaleMoney = $Coupondetails['value2'];
                }
            }else{
                throw new ParameterException([
                    'msg' => '优惠券信息异常'
                ]);
            }
        }
        if($this->memberId){
            $user = User::where(['id'=>$this->uid,'typeId'=>$this->memberId])->where('memberendtime',['=',0],['>',time()],'OR')->find();
            if($user){
                $Usermemberhistory = Usermemberhistory::where(['userId'=>$user->id,'membertype_id'=>$this->memberId])->find();
                if($Usermemberhistory){
                    //会员价
                    if($Usermemberhistory->isMemBerShop == 0){
                        if($status['orderPrice']>=$status['ordermemberPrice']){
                            $MemberDiscount = $status['orderPrice']-$status['ordermemberPrice'];
                            $status['orderPrice'] = $status['ordermemberPrice'];
                        }


                    }else{
                        //会员折扣
                        $discountprice = $status['orderPrice'] * ($Usermemberhistory->memberDiscounts*10/100);
                        $MemberDiscount = $status['orderPrice'] - $discountprice;
                        $status['orderPrice'] = $discountprice;

                    }

                    $this->oldMemberPrice = $MemberDiscount;

                }

            }
        }
        //运费
        if($this->freight){
            $status['orderPrice'] += $this->freight;
        }
        //包装费
        if($this->packingfee){
            $status['orderPrice'] += $this->packingfee;
        }

        if($status['orderPrice'] <= 0){
            $status['orderPrice'] = 1;
        }
        //开始创建订单
        $orderSnap = $this->snapOrder($status);

        $order = $this->createOrder($orderSnap);
        $order['pass'] = true;
        return $order;

    }

    private function ischeckaddress($orderdata){
        if(isset($orderdata['deliverAddress']) && !empty($orderdata['deliverAddress']) && isset($orderdata['userName']) && !empty($orderdata['userName']) && isset($orderdata['userPhone']) && !empty($orderdata['userPhone'])){
            return true;
        }else{
            return false;
        }
    }


    //创建订单
    private function createOrder($orderSnap){
        Db::startTrans();
        try
        {
            $order = \app\common\model\Order::get($this->orderId);
            if($order){
                //修改订单
                $order->content = $this->content;
                $order->deliverAddress = $this->deliverAddress;
                $order->userName = $this->userName;
                $order->userPhone = $this->userPhone;
                $order->subscribeDate = $this->subscribeDate;
                $order->couponId = $this->couponId;
                $order->total = $orderSnap['orderPrice'];
                $order->oldSaleMoney = $this->oldSaleMoney;
                $order->oldMemberPrice = $this->oldMemberPrice;
                $order->freight = $this->freight;
                $order->packingfee = $this->packingfee;
                $order->save();
                Db::commit();
                return [
                    'orderNO' => $order->orderNO,
                    'orderId' => $order->id,
                    'create_time' => $order->create_time
                ];
            }
            $orderNo = $this->makeOrderNo();
            $order = new \app\common\model\Order();
            $order->id = $this->orderId;
            $order->createUser = $this->uid;
            $order->tenantId = $this->tenantid;
            $order->storeId = $this->storeid;
            $order->saleRuleId = $this->saleRuleId;
            $order->content = $this->content;
            $order->deliverAddress = $this->deliverAddress;
            $order->userName = $this->userName;
            $order->userPhone = $this->userPhone;
            $order->subscribeDate = $this->subscribeDate;
            $order->type = $this->ordertype;
            $order->orderNO = $orderNo;
            $order->couponId = $this->couponId;
            $order->total = $orderSnap['orderPrice'];
            $order->oldSaleMoney = $this->oldSaleMoney;
            $order->oldMemberPrice = $this->oldMemberPrice;
            $order->freight = $this->freight;
            $order->packingfee = $this->packingfee;
            $order->total_count = $orderSnap['totalCount'];
            $order->userAddressId = $orderSnap['snapAddressId'];
            $order->save();

            $orderId = $order->id;
            $create_time = $order->create_time;
            $i = 0;
            foreach ($this->oProducts as &$p)
            {
                $p['id'] = BaseHelper::getUUID();
                $p['orderId'] = $orderId;
                $p['productName'] = $orderSnap['pStatus'][$i]['title'];
                $p['productImg'] =  $orderSnap['pStatus'][$i]['imgUrl'];
                $p['specid'] =  isset($orderSnap['pStatus'][$i]['specid'])?$orderSnap['pStatus'][$i]['specid']:null;
                $p['productSpec'] =  isset($orderSnap['pStatus'][$i]['specDetails1'])?$orderSnap['pStatus'][$i]['specDetails1']:null;
                $p['productSpec1'] =  isset($orderSnap['pStatus'][$i]['specDetails2'])?$orderSnap['pStatus'][$i]['specDetails2']:null;
                $p['productSpec2'] =  isset($orderSnap['pStatus'][$i]['specDetails3'])?$orderSnap['pStatus'][$i]['specDetails3']:null;
                $p['price'] = $orderSnap['pStatus'][$i]['currentPrice'];
                $p['userId'] = $this->uid;
                $p['tenantId'] = $this->tenantid;
                $i++;
            }
            $orderProduct = new Orderproductdetail();
            $orderProduct->saveAll($this->oProducts,false);
            //如果有优惠券（则改变此优惠券为被占用状态）
            if($this->couponId){
                $Couponuse = Couponuse::where(['couponId'=>$this->couponId,'userId'=>$this->uid,'storeId'=>$this->storeid,'status'=>0])->find();
                if($Couponuse){
                    $Couponuse->status = 2;
                    $Couponuse->save();
                }

            }
            Db::commit();
            return [
                'orderNO' => $orderNo,
                'orderId' => $orderId,
                'create_time' => $create_time
            ];

        }catch (Exception $e){
            Db::rollback();
            throw $e;
        }
    }


    // 生成订单快照(历史订单信息，不随着商品的变化而变化)
    private function snapOrder($status){
        $snap = [
            'orderPrice' => 0,
            'ordermemberPrice' => 0,
            'totalCount' => 0,
            'pStatus' => [],
            'snapAddressId' => null,
            'snapName' => '',
            'snapImg' => ''
        ];
        $snap['orderPrice'] = $status['orderPrice'];
        $snap['ordermemberPrice'] = $status['ordermemberPrice'];
        $snap['totalCount'] = $status['totalCount'];
        $snap['pStatus'] = $status['pStatusArray'];
        //$snap['snapAddressId'] = $this->getUserAddress();
        $snap['snapName'] = $this->products[0]['title'];
        $snap['snapImg'] = $this->products[0]['imgUrl'];
        if (count($this->products) > 1)
        {
            $snap['snapName'] .= '等';
        }
        return $snap;
    }


    /**
     * 生成订单号
     * @return string
     */
    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }

    /**
     * 获取收货地址
     * @return mixed
     * @throws UserException
     */
    private function getUserAddress()
    {
        $userAddress = Useraddress::where('userId', '=', $this->uid)->find();
        if (!$userAddress)
        {
            throw new UserException(
                [
                    'msg' => '用户收货地址不存在，下单失败',
                    'errorCode' => 60001,
                ]);
        }
        return $userAddress->id;
    }

    /**
     * 根据订单ID进行库存量检测
     * @param $orderID
     * @return array
     */
    public function checkOrderStock($orderID){
        $oProducts = Orderproductdetail::where('orderId','=',$orderID)->select();
        $this->oProducts = $oProducts;
        $this->products = $this->getProductsByOrder($oProducts);
        $status = $this->getOrderStatus();
        return $status;
    }

    /**
     * 获取订单状态
     * @return array
     */
    private function getOrderStatus(){
        $status = [
            'pass' => true,
            'orderPrice' => 0,
            'ordermemberPrice' => 0,
            'totalCount' => 0,
            'pStatusArray' => []
        ];
        $temp = [];
        foreach ($this->oProducts as $oProduct){
            $oPID = $oProduct['productId'];
            $products = $this->products;
            $oCount = $oProduct['count'];

            //$pStatus = $this->getProductStatus($oProduct['productId'],$oProduct['count'],$this->products);



            $pIndex = -1;
            $pStatus = [
                'id' => null,
                'havestoreCount' => false,
                'counts' => 0,
                'currentPrice' => 0,
                'title' => '',
                'totalPrice' => 0,
                'totalmemberPrice' => 0,
                'imgUrl' => null,
                'specDetails1' => null,
                'specDetails2' => null,
                'specDetails3' => null
            ];
            $m = 0;
            for ($i = 0; $i < count($products); $i++)
            {
                if($products[$i]['specClass'] == 2){
                    if ($oPID == $products[$i]['id'])
                    {
                        if(!in_array($products[$i]['specid'],$temp)){
                            if($m == 0){
                                $pIndex = $i;
                                array_push($temp,$products[$i]['specid']);
                            }
                            $m++;
                        }


                    }
                }else{
                    if ($oPID == $products[$i]['id'])
                    {
                        $pIndex = $i;
                    }
                }

            }
            if($pIndex == -1){
                // 客户端传递的productId有可能根本不存在
                throw new OrderException([
                    'msg' => 'id为' . $oPID . '的商品不存在，创建订单失败'
                ]);
            }else{
                $product = $products[$pIndex];
                $pStatus['id'] = $product['id'];
                $pStatus['title'] = $product['title'];
                $pStatus['counts'] = $oCount;
                $pStatus['currentPrice'] = $product['currentPrice'];
                $pStatus['imgUrl'] = $product['imgUrl'];
                $pStatus['totalPrice'] = $product['currentPrice'] * $oCount;
                $pStatus['totalmemberPrice'] = $product['memberPrice'] * $oCount;
                if(isset($product['specDetails1']) && !empty($product['specDetails1'])){
                    $pStatus['specDetails1'] = $product['specDetails1'];
                }
                if(isset($product['specDetails2']) && !empty($product['specDetails2'])){
                    $pStatus['specDetails2'] = $product['specDetails2'];
                }
                if(isset($product['specDetails3']) && !empty($product['specDetails3'])){
                    $pStatus['specDetails3'] = $product['specDetails3'];
                }
                if(isset($product['specid']) && !empty($product['specid'])){
                    $pStatus['specid'] = $product['specid'];
                }

                if($product['isStore'] == 0){
                    //如果不限制库存
                    $pStatus['havestoreCount'] = true;
                }else{
                    if($product['storeCount'] - $oCount >= 0){
                        $pStatus['havestoreCount'] = true;
                    }
                }


            }




            if(!$pStatus['havestoreCount']){
                $status['pass'] = false;
            }
            $status['orderPrice'] += $pStatus['totalPrice'];
            $status['ordermemberPrice'] += $pStatus['totalmemberPrice'];
            $status['totalCount'] += $pStatus['counts'];
            $status['title'] = $pStatus['title'];
            array_push($status['pStatusArray'], $pStatus);

        }

        return $status;
    }

    /**
     * 获取商品状态 （主要是做库存量检测，发现购物车有一种商品库存量不足，整个订单库存量检测不通过）
     * @param $oPID
     * @param $oCount
     * @param $products
     * @return array
     * @throws OrderException
     */
    /*private function getProductStatus($oPID,$oCount,$products){
        $pIndex = -1;
        $pStatus = [
            'id' => null,
            'havestoreCount' => false,
            'counts' => 0,
            'currentPrice' => 0,
            'title' => '',
            'totalPrice' => 0,
            'totalmemberPrice' => 0,
            'imgUrl' => null,
            'specDetails1' => null,
            'specDetails2' => null,
            'specDetails3' => null
        ];
        for ($i = 0; $i < count($products); $i++)
        {
            if ($oPID == $products[$i]['id'])
            {
                $pIndex = $i;
            }
        }
        if($pIndex == -1){
            // 客户端传递的productId有可能根本不存在
            throw new OrderException([
                'msg' => 'id为' . $oPID . '的商品不存在，创建订单失败'
            ]);
        }else{
            $product = $products[$pIndex];
            $pStatus['id'] = $product['id'];
            $pStatus['title'] = $product['title'];
            $pStatus['counts'] = $oCount;
            $pStatus['currentPrice'] = $product['currentPrice'];
            $pStatus['imgUrl'] = $product['imgUrl'];
            $pStatus['totalPrice'] = $product['currentPrice'] * $oCount;
            $pStatus['totalmemberPrice'] = $product['memberPrice'] * $oCount;
            if(isset($product['specDetails1']) && !empty($product['specDetails1'])){
                $pStatus['specDetails1'] = $product['specDetails1'];
            }
            if(isset($product['specDetails2']) && !empty($product['specDetails2'])){
                $pStatus['specDetails2'] = $product['specDetails2'];
            }
            if(isset($product['specDetails3']) && !empty($product['specDetails3'])){
                $pStatus['specDetails3'] = $product['specDetails3'];
            }
            if(isset($product['specid']) && !empty($product['specid'])){
                $pStatus['specid'] = $product['specid'];
            }

            if($product['isStore'] == 0){
                //如果不限制库存
                $pStatus['havestoreCount'] = true;
            }else{
                if($product['storeCount'] - $oCount >= 0){
                    $pStatus['havestoreCount'] = true;
                }
            }


        }
        return $pStatus;
    }*/

    /**
     * 根据订单查找真实的商品信息
     * @param $oProducts
     * @return mixed
     */
    private function getProductsByOrder($oProducts){

        $oPIDs = [];
        $specIDS = [];
        if(!is_array($oProducts)){
            throw new ParameterException([
                'msg' => '缺少购买的商品信息'
            ]);
        }
        foreach ($oProducts as $item){
            if(isset($item['specid'])){
                array_push($specIDS,$item['specid']);
            }
            array_push($oPIDs,$item['productId']);
        }
        $products = [];
        //$products = Product::all($oPIDs)->visible(['id','currentPrice','memberPrice','storeCount','isStore','title','imgUrl','specClass'])->toArray();
        foreach ($oPIDs as $v){
            //为什么要用循环，防止把同一商品的不同规格同时加到购物车
            $res = Product::where('id',$v)->field('id,currentPrice,memberPrice,storeCount,isStore,title,imgUrl,specClass')->find()->toArray();
            array_push($products,$res);
        }
        if(count($specIDS)>0){
            $specs = Productspecgroups::all($specIDS)->visible(['id','specDetails1','specDetails2','specDetails3','currentPrice','memberPrice','storeCount','isStore','productId'])->toArray();
            $temp = [];
            foreach ($products as &$product){
                if($product['specClass']==2){
                    $i = 0;
                    foreach ($specs as $spec){
                        if($spec['productId']==$product['id']){
                            if(!in_array($spec['id'],$temp)){
                                if($i == 0){
                                    $product['currentPrice'] = $spec['currentPrice'];
                                    $product['memberPrice'] = $spec['memberPrice'];
                                    $product['specDetails1'] = $spec['specDetails1'];
                                    $product['specDetails2'] = $spec['specDetails2'];
                                    $product['specDetails3'] = $spec['specDetails3'];
                                    $product['storeCount'] = $spec['storeCount'];
                                    $product['specid'] = $spec['id'];
                                    array_push($temp,$spec['id']);
                                }
                                $i++;

                            }

                        }
                    }
                }
            }
        }
        return $products;
    }

    //用户订单确认收货
    public function ConfirmCollectGoods($orderID){
        Db::startTrans();
        try{
            $orderModel = new \app\common\model\Order();
            $order = $orderModel->where('id',$orderID)->find();
            if(!$order){
                throw new ParameterException([
                    'msg' => '该订单不存在'
                ]);
            }
            if($order->status!=DictConstant::OrderAlreadyShipped){
                throw new ParameterException([
                    'msg' => '该订单状态不对'
                ]);
            }
            $orderuser = $order->createUser;
            $order->status = DictConstant::OrderCompleted;
            $order->completedtime = time();
            $order->save();
            $this->IncCommission($orderuser,$order->saleRuleId,$order->id);
            $Orderproductdetail = new Orderproductdetail();
            $orderpro = $Orderproductdetail->where('orderId', $order->id)->select();
            $list = [];
            foreach ($orderpro as $value) {
                array_push($list, ['id' => $value['id'], 'oldStatus' => DictConstant::OrderCompleted]);
            }
            $Orderproductdetail->saveAll($list);
            //判断是否需要赠送积分
            $Integral = new Integral();
            $Integral->XiaofeiSongjiFen($order);
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'确认收货成功','确认收货成功');
        }catch (Exception $ex){
            Db::rollback();
            Log::record($ex);
            return show(config('status.ERROR_STATUS'),'确认收货失败',$ex);
        }
    }
    //确认收货时如果订单用户有上级，则要为上级用户抽取佣金
    private function IncCommission($orderuser,$saleRuleId,$orderId){
        $user = User::get($orderuser);
        if($user->chiefUserId && $saleRuleId){
            $chiefUser = User::get($user->chiefUserId);
            $ordercom = Ordercommission::where('orderId','=',$orderId)->find();
            if($ordercom->status == 0){
                $yongjin = $ordercom->total * ($ordercom->proportion / 100);
                $ordercom->status = 2;
                $ordercom->save();
                $chiefUser->setInc('totalIncome',$yongjin);

            }
        }
    }

    //取消未付款订单
    public function cancelOrder($orderId){
        Db::startTrans();
        try{
            $order = \app\common\model\Order::get($orderId);
            if(!$order){
                throw new ParameterException([
                    'msg' => '该订单不存在'
                ]);
            }
            if($order->status!=DictConstant::OrderPendingPayment){
                throw new ParameterException([
                    'msg' => '该订单不能取消了'
                ]);
            }
            $order->status = DictConstant::OrderInvalid;
            $order->invalid_time = time();
            $order->save();
            $Orderproductdetail = new Orderproductdetail();
            $orderpro = $Orderproductdetail->where('orderId', $order->id)->select();
            $list = [];
            foreach ($orderpro as $value) {
                array_push($list, ['id' => $value['id'], 'oldStatus' => DictConstant::OrderInvalid]);
            }
            $Orderproductdetail->saveAll($list);
            //如果使用了优惠券，则要返还优惠券
            if($order->couponId){
                $couponuse = Couponuse::where(['couponId'=>$order->couponId,'userId'=>$order->createUser,'storeId'=>$order->storeId,'status'=>2])->find();
                if($couponuse){
                    $couponuse->status = 0;
                    $couponuse->save();
                }
            }
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'取消订单成功','取消订单成功');

        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),$ex->msg,'取消订单失败');
        }
    }

    //订单申请售后
    public function refund($postData){
        Db::startTrans();
        try{
            //检查该订单状态
            $order = \app\common\model\Order::get($postData['orderId']);
            $linkType = $order->linkType;

            $orders = Orderproductdetail::where('orderId',$postData['orderId'])->select();
            $orderpro = Orderproductdetail::where(['orderId'=>$postData['orderId'],'productId'=>$postData['productId']])->find();
            $orderrefund = Refundorder::where(['orderNO'=>$order->orderNO,'productId'=>$postData['productId']])->find();
            $orderrefundnum = Refundorder::where('orderNO',$order->orderNO)->where('status',['=',Refundorder::STATUS_2],['=',Refundorder::STATUS_4],'OR')->count();
            $this->checkorder($order,$orderpro,$orderrefund);
            $allprice = 0;
            foreach ($orders as $v){
                if($linkType == 0){
                    $allprice += ($v['price']/100 * $v['count']);
                }elseif ($linkType == 1){
                    $allprice += ($v['gprice']/100 * $v['count']);
                }else{

                }

            }
            //运费和包装费;
            $otherprice = ($order->freight + $order->packingfee)/100;
            //计算退款金额
            if($linkType == 0){
                $price = $orderpro->price/100  * $orderpro->count;
            }elseif ($linkType == 1){
                $price = $orderpro->gprice/100  * $orderpro->count;
            }else{

            }

            if($order->oldSaleMoney==0 && $order->oldMemberPrice==0){
                if(count($orders) - $orderrefundnum > 1){
                    $refundprice = $price;
                }else{
                    //最后一笔订单要退邮费和包装费
                    $refundprice = $price + $otherprice;
                }

            }else{
                if(count($orders) - $orderrefundnum > 1){
                    if($order->oldSaleMoney != 0){
                        $refundprice = $price-($order->oldSaleMoney/100)*$price/$allprice;
                    }else{
                        $refundprice = $price-($order->oldMemberPrice/100)*$price/$allprice;
                    }
                }else{
                    //最后一笔订单要退邮费和包装费
                    if($order->oldSaleMoney != 0){
                        $refundprice = $price-($order->oldSaleMoney/100)*$price/$allprice + $otherprice;
                    }else{
                        $refundprice = $price-($order->oldMemberPrice/100)*$price/$allprice + $otherprice;
                    }
                }

            }
            $refundprice = sprintf("%.2f",$refundprice) * 100;

            if($refundprice>$order->total){
                throw new ParameterException([
                    'msg' => '申请售后的金额不能大于订单总金额'
                ]);
            }
            if($refundprice <= 0){
                $refundprice = 1;
            }
            //创建售后订单
            $refund = new Refundorder();
            $out_refund_no = Order::makeOrderNo();
            $refund->id = BaseHelper::getUUID();
            $refund->orderNO = $order->orderNO;
            $refund->orderProductDetailId = $orderpro->id;
            $refund->productId = $postData['productId'];
            $refund->reason = isset($postData['reason'])?$postData['reason']:NULL;
            $refund->count = $orderpro->count;
            $refund->storeId = $order->storeId;
            $refund->tenantId = $order->tenantId;
            $refund->userId = $order->createUser;
            $refund->out_refund_no = $out_refund_no;
            $refund->transaction_Id = $order->transaction_Id;
            $refund->refund_fee = $refundprice;
            $refund->oldTotal = $order->total;
            $refund->save();

            //是否上传了售后凭证
            if($postData['Imgs']){
                $proofrefund = new Proofrefund();
                $proofrefund->id = BaseHelper::getUUID();
                $proofrefund->refundId = $refund->id;
                $proofrefund->imgUrl = $postData['Imgs'];
                $proofrefund->tenantId = $refund->tenantId;
                $proofrefund->storeId = $refund->storeId;
                $proofrefund->save();
            }

            $order->status = DictConstant::Order_Reefund;
            $order->save();

            Db::commit();
            $data =  [
                'orderId' => $postData['orderId'],
                'productId' => $refund->productId,
                'out_refund_no' => $out_refund_no,
                'create_time' => $refund->create_time,
                'refund_fee' => $refund->refund_fee
            ];
            return show(config('status.SUCCESS_STATUS'),'创建售后订单成功',$data);
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),$ex->msg,'创建售后订单失败');
        }

    }

    private function checkorder($order,$orderpro,$orderrefund){
        if(!$order){
            throw new ParameterException([
                'msg' => '该订单不存在'
            ]);
        }
        if(!$orderpro){
            throw new ParameterException([
                'msg' => '该订单商品不存在'
            ]);
        }
//        if($order->status!=2 && $order->status!=8){   //status = 3 已经发货订单 用户与商家协商自行处理
//            throw new ParameterException([
//                'msg' => '该订单不能售后'
//            ]);
//        }
        if($orderrefund){
            throw new ParameterException([
                'msg' => '一个订单只能进行一次售后'
            ]);
        }

        if($orderpro->oldStatus != 2 && $orderpro->oldStatus != 3 && $orderpro->oldStatus != 8){
            throw new ParameterException([
                'msg' => '此商品不能进行售后了'
            ]);
        }
    }



}